package com.szxy.miaosha.exception;

import com.szxy.miaosha.utils.CodeMsg;
import com.szxy.miaosha.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: zwz
 * @Date:2020/9/7 20:28
 * @Description:com.szxy.miaosha.exception
 * @Version:1.0
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    public Result AllExceptionHandler(HttpServletRequest request, Throwable e) {
        // 控制台打印异常信息
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCm());
        } else if (e instanceof BindException) {
            BindException be = (BindException) e;
            List<ObjectError> allErrors = be.getAllErrors();
            String message = allErrors.get(0).getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(message));
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }

}
